package com.songlanyun.modules.marketing.groupbuy.controller.admin;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;

import com.songlanyun.common.annotation.RepeatSubmit;
import com.songlanyun.common.annotation.SysLog;
import com.songlanyun.common.enums.MarketingConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.custom.MathUtils;
import com.songlanyun.common.validator.ValidatorUtils;
import com.songlanyun.modules.exception.GoodsExceptionEnum;
import com.songlanyun.modules.exception.MarketingException;
import com.songlanyun.modules.goods.entity.Goods;
import com.songlanyun.modules.goods.service.GoodsService;
import com.songlanyun.modules.marketing.groupbuy.entity.GroupBuyActivity;
import com.songlanyun.modules.marketing.groupbuy.entity.GroupBuyGoodsSku;
import com.songlanyun.modules.marketing.groupbuy.model.dto.GroupBuyActivityGoodsDTO;
import com.songlanyun.modules.marketing.groupbuy.service.GroupBuyActivityService;
import com.songlanyun.modules.marketing.seckill.entity.SeckillGoodsSku;
import com.songlanyun.modules.marketing.seckill.model.dto.SeckillActivityGoodsDTO;
import com.songlanyun.modules.user.controller.AbstractController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.songlanyun.modules.marketing.groupbuy.entity.GroupBuyActivityGoods;
import com.songlanyun.modules.marketing.groupbuy.service.GroupBuyActivityGoodsService;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.R;

import javax.annotation.Resource;


/**
 * 拼团活动商品表
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2020-11-27 14:03:38
 */
@RestController
@RequestMapping("admin/groupbuy/activitygoods")
public class GroupBuyActivityGoodsAdminController extends AbstractController {
    @Autowired
    private GroupBuyActivityGoodsService groupBuyActivityGoodsService;

    @Resource
    private GoodsService goodsService;

    @Resource
    private GroupBuyActivityService groupBuyActivityService;

    /**
     * 查询指定拼团活动商品列表
     */
    @GetMapping("/getGoodsList")
//    @RequiresPermissions("groupbuy:groupBuyActivityGoods:list")
    public R list(@RequestParam Map<String, Object> params) {
        params.put("shop_id", getShopId(true));
        PageUtils page = groupBuyActivityGoodsService.goodsPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 获取拼团活动商品信息 及 商品sku信息
     * <p>
     * 拼团拼团商品id
     */
    @GetMapping("/info/{id}")
//    @RequiresPermissions("seckill:seckillActivityGoods:info")
    public R info(@PathVariable("id") Long id) {
        GroupBuyActivityGoods groupBuyActivityGoods = groupBuyActivityGoodsService.getGoodsAndSkuById(id);

        return R.ok().put("data", groupBuyActivityGoods);
    }

    /**
     * 添加/更新 拼团活动商品
     */
    @SysLog("添加/更新 拼团活动商品")
    @RepeatSubmit("2")
    @PostMapping("/save")
//    @RequiresPermissions("groupbuy:groupBuyActivityGoods:save")
    public R save(@RequestBody GroupBuyActivityGoodsDTO dto) {
        verify(dto);//校验
        ValidatorUtils.validateEntity(dto);
        groupBuyActivityGoodsService.saveGoods(dto);

        return R.ok();

    }


    /**
     * 删除
     */
    @SysLog("删除拼团活动商品")
    @DeleteMapping("/delete/{id}")
//    @RequiresPermissions("seckill:seckillActivityGoods:delete")
    public R delete(@PathVariable("id") Long id) {
        groupBuyActivityGoodsService.deleteById(id);

        return R.ok();
    }

    private void verify(Long goodsId, Long seckillId) {
        Long shopId = getShopId(true);
        //校验商品是否是该商家的
        Goods goods = goodsService.getByShopIdAndId(shopId, goodsId);
        if (goods == null) {
            throw new RRException(GoodsExceptionEnum.GOODS_NOT_EXISTS);
        }
        //校验拼团活动是否是该商家的
        groupBuyActivityService.getByShopIdAndId(shopId, seckillId, true);

    }

    /**
     * 检验
     */
    private void verify(GroupBuyActivityGoodsDTO dto) {
        Long goodsId = dto.getGoodsId();
        Long seckillId = dto.getGroupBuyId();

        Long shopId = getShopId(true);
        //1、校验商品是否是该商家的
        Goods goods = goodsService.getByShopIdAndId(shopId, goodsId);
        if (goods == null) {
            throw new RRException(GoodsExceptionEnum.GOODS_NOT_EXISTS);
        }
        //2、校验秒杀活动是否是该商家的
        groupBuyActivityService.getByShopIdAndId(shopId, seckillId, true);

        //3、校验活动打折方式
        if (dto.getPriceType().equals(MarketingConstant.PriceType.FIXED_DISCOUNT.getCode())) {
            //固定折扣  大于1折，小于10折
            if (dto.getDiscount().compareTo(new BigDecimal("0.1")) < 0
                    || dto.getDiscount().compareTo(new BigDecimal("10.0")) > 0) {
                throw new RRException(MarketingException.DISCOUNT_OUT_OF_RANGE);
            }

        } else if (dto.getPriceType().equals(MarketingConstant.PriceType.PRICE_FIXED_BY.getCode())) {
            //固定减价 不能小于0
            if (dto.getFixPrice().compareTo(BigDecimal.ZERO) < 0) {
                throw new RRException(MarketingException.FIXPRICE_OUT_OF_RANGE);
            }
        }

        if(dto.getRealStockTotal()<=dto.getInitSaleNum())
        {
            throw new RRException(MarketingException.REAL_STOCK_TOTAL_LT_INIT_SALE_NUM);
        }

        //4、校验活动价格
        List<GroupBuyGoodsSku> skuList = dto.getGroupBuyGoodsSkuList();
        if (skuList != null && skuList.size() > 0) {
            for (GroupBuyGoodsSku sku : skuList) {
                //活动价格不能小于0
                if (sku.getActivityPrice().compareTo(BigDecimal.ZERO) < 0) {
                    throw new RRException(MarketingException.ACTIVITY_PRICE_OUT_OF_RANGE);
                }

                //活动价格需要小于原价
                if (MathUtils.subtract(sku.getActivityPrice(), sku.getSalePrice())
                        .compareTo(BigDecimal.ZERO) >= 0) {
                    throw new RRException(MarketingException.ACTIVITY_PRICE_LT_SALE_PRICE);
                }
            }

        }
    }

}
